#!/bin/bash
svnDiffFile="/tmp/svndiff.file"
resultFile="./codecount.txt"
SVN_OPTION="--no-auth-cache --non-interactive"
allDeleteLine=0
allAddLine=0
totalChange=0
branchUrl=""
origRev=""
allRevRange=""

function ShowUsage()
{
	echo "countallChanges.sh -b branch_url -r rev_range"
	exit
}
function GetAllRev()
{
	local brUrl="$1"
	local verRange="$2"
	local allV=""
	allV="` svn.shc log $brUrl -r $verRange $SVN_OPTION | grep "^r[0-9][0-9]*" | awk '{print $1}' | tr -d 'r' | tr "\n" " "`"
	echo "$allV"
}
function GenSvnDiffFile()
{
	local brUrl="$1"
	local rev=$2
	local preRev=$(( ${rev} - 1 ));
	svn.shc diff $brUrl -r $preRev:$rev  $SVN_OPTION > $svnDiffFile
}
function CountDiffLine()
{
	local version="$1"
	local df="$2"
	lineAdd=`grep "^+" $df | grep -v "^+++" | sed 's/^.//' | sed '/^$/d' | wc -l`
	lineDel=`grep "^-" $df | grep -v "^---" | sed 's/^.//' | sed '/^$/d' | wc -l`
	allAddLine=$(( $allAddLine + $lineAdd ))
	allDeleteLine=$(( $allDeleteLine + $lineDel ))
	echo -e "版本$version中：	新增$lineAdd,删除$lineDel\n------------------|\n\n"
}

if [ $# -lt 4 ]; then
	ShowUsage
fi
while [ $# -gt 0 ]; do
	case $1 in 
	-b|--branch)
		shift;
		if [ "$1" == "" ];then
			ShowUsage
		fi
		branchUrl="$1"
	;;
	
	-r|--revision)
		shift;
		if [ "$1" == "" ];then
			ShowUsage
		fi
		origRev="$1"
	;;
	
	*)
		ShowUsage
	;;
	esac
	shift;
done
echo "branchUrl=$branchUrl,origRev=$origRev"
allRevRange="`echo $origRev | tr ',' ' '`"
for v in $allRevRange; do
	allRev=(`GetAllRev $branchUrl $v`)
	for r in ${allRev[@]}; do
		GenSvnDiffFile $branchUrl $r
		CountDiffLine $r $svnDiffFile
	done
done

totalChange=$(($allDeleteLine + $allAddLine))
length="$(( ${#allRev[*]} -1 ))"
echo "====================>
`date`
Code count of $branchUrl under version \"$origRev\"(r${allRev[0]}:r${allRev[${length}]})
总删除行=$allDeleteLine
总新增行=$allAddLine
总修改行(总删除行+总新增行)=$totalChange
<====================" >> $resultFile
echo "See at $resultFile"
